import storage from 'store'
import { login, getInfo, logout } from '@/api/login'
import { ACCESS_TOKEN, COMPANY, GROUP, ROLE } from '@/store/mutation-types'

const user = {
  state: {
    token: '',
    name: '',
    avatar: '',
    info: {},
    companies: {},
    company: '',
    group: '',
    role: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_COMPANIES: (state, companies) => {
      state.companies = companies
    },
    SET_COMPANY: (state, company) => {
      state.company = company
    },
    SET_GROUP: (state, group) => {
      state.group = group
    },
    SET_ROLE: (state, role) => {
      state.role = role
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const result = response.result
          let company = ''
          storage.set(ACCESS_TOKEN, result.access_token, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', result.access_token)
          for (const k in result.company_names) {
            company = k
            break
          }
          storage.set(COMPANY, company)
          commit('SET_COMPANY', company)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const menus = response.result.antd_menus
          const info = response.result.user_info
          if (menus.length > 0) {
            commit('SET_INFO', info)
          } else {
            reject(new Error('getInfo: roles must be a non-null array !'))
          }
          storage.set(GROUP, info.group2)
          storage.set(ROLE, info.group_type)
          commit('SET_COMPANIES', response.result.company_names)
          commit('SET_NAME', info.username)
          commit('SET_AVATAR', info.avatar)
          commit('SET_GROUP', info.group2)
          commit('SET_ROLE', info.group_type)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          resolve()
        }).catch(() => {
          resolve()
        }).finally(() => {
          storage.remove(ACCESS_TOKEN)
          storage.remove(GROUP)
          storage.remove(COMPANY)
          storage.remove(ROLE)
          commit('SET_TOKEN', '')
          commit('SET_COMPANIES', {})
          commit('SET_COMPANY', '')
          commit('SET_GROUP', '')
          commit('SET_ROLE', '')
        })
      })
    }
  }
}

export default user
